import moment from 'moment';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const BMF = require('browser-md5-file');

export interface IComputeFileHashListener {
  success: (md5: string) => void;
  error: (err: any) => void;
  progress: (progress: number, percent: string) => void;
  complete: (err: any, md5: string) => void;
}

/**
 * 计算文件Hash
 * @param file
 * @param listener
 */
export function computeFileHash(file: File, listener: Partial<IComputeFileHashListener>) {
  const bmf = new BMF();
  const { success, error, progress: onProgress, complete } = listener;
  return new Promise((resolve, reject) => {
    bmf.md5(
      file,
      (err: any, md5: string) => {
        if (!err) {
          resolve(md5);
          success && success(md5);
        } else {
          reject(err);
          error && error(err);
        }
        complete && complete(err, md5);
      },
      (progress: number) => {
        const per = Number((progress * 100).toFixed(2));
        const percent = per >= 100 ? 100 : per === 0 ? 0 : per;
        onProgress && onProgress(progress, `${percent}%`);
      }
    );
  });
}

export function toPercent(progress: number) {
  return `${(progress * 100).toFixed(2)}%`;
}

/**
 * 格式文件时间
 * @param time
 */
export function formatTime(time: number) {
  return moment(time).format('YYYY-MM-DD HH:mm');
}
